const fs=require("fs")
const {UPLOAD_PICTURE} =require("../config/path")
const MomentService = require('../service/moment.service')
const labelService=require("../service/label.service")
const fileService=require("../service/file.service")


class momentController {
  async create(ctx, next) {
    const { content } = ctx.request.body
    // 谁发布动态
    const { id } = ctx.user
    // console.log(id)
    const result = await MomentService.create(content, id)
    ctx.body = {
      code: 0,
      message: '创建用户动态成功',
      data: result,
    }
  }
  async list(ctx, next) {
    const { offset, size } = ctx.query
    // console.log(offset, size)
    const result = await MomentService.queryList(offset, size)
    // console.log(result)
    ctx.body = {
      code: 0,
      data: result,
    }
  }
  async detail(ctx, next) {
    const { momentId } = ctx.params
    // 根据id查询
    const result = await MomentService.queryById(momentId)
    // console.log(result)
    ctx.body = {
      code: 0,
      data: result,
    }
  }
  async update(ctx, next) {
    const { momentId } = ctx.params
    const { content } = ctx.request.body
    // console.log(momentId, content)
    // 根据id修改数据
    const result = await MomentService.updteById(momentId, content)
    //    console.log(result)
    ctx.body = {
      code: 0,
      data: result,
    }
  }
  async remove(ctx, next) {
    const { momentId } = ctx.params
    const result = await MomentService.remove(momentId)
    // console.log(result)
    ctx.body = {
      code: 0,
      message: '删除成功',
      data: result,
    }
  }
   // 为动态添加标签
   async addLabels(ctx, next) {
    const { labels } = ctx
    const { momentId } = ctx.params
    console.log(labels, momentId)
    try {
      for (const label of labels) {
        // 判断label_id是否已经和moment_id已经存在关系
        const isExists = await MomentService.hasLabel(momentId, label.id)
        console.log(isExists)
        if (!isExists) {
          // 不存在label插入
          const result = await labelService.addLabel(momentId, label.id)
        }
      }
      ctx.body = {
        code: 0,
        message: '为动态添加标签成功',
      }
    } catch (error) {
      ctx.body = {
        code: -3001,
        message: '为动态添加标签失败！',
      }
    }
  }
  // 为动态添加图片
  async fileInfo(ctx, next) {
    let { filename } = ctx.params;
    const fileInfo = await fileService.getFileByFilename(filename);
    const { type } = ctx.query;
    // console.log(type)
    const types = ["small", "middle", "large"];
    if (types.some(item => item === type)) {
      filename = filename + '-' + type;
    }

    ctx.response.set('content-type', fileInfo.mimetype);
    // console.log(UPLOAD_PICTURE)
    ctx.body = fs.createReadStream(`${UPLOAD_PICTURE}/${filename}`);
  }
}
module.exports = new momentController()
